<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      python/Django框架/19-Django高级之-缓存 | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>python/Django框架/19-Django高级之-缓存</h2>



  <p class="post-date">2020-09-24</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h2 id="一-缓存介绍"><a href="#一-缓存介绍" class="headerlink" title="一 缓存介绍"></a>一 缓存介绍</h2><p>在动态网站中,用户所有的请求,服务器都会去数据库中进行相应的增,删,查,改,渲染模板,执行业务逻辑,最后生成用户看到的页面.</p>
<p>当一个网站的用户访问量很大的时候,每一次的的后台操作,都会消耗很多的服务端资源,所以必须使用缓存来减轻后端服务器的压力.</p>
<p>缓存是将一些常用的数据保存内存或者memcache中,在一定的时间内有人来访问这些数据时,则不再去执行数据库及渲染等操作,而是直接从内存或memcache的缓存中去取得数据,然后返回给用户.</p>
<h2 id="二-Django中的6种缓存方式"><a href="#二-Django中的6种缓存方式" class="headerlink" title="二 Django中的6种缓存方式"></a>二 Django中的6种缓存方式</h2><ul>
<li>开发调试缓存</li>
<li>内存缓存</li>
<li>文件缓存</li>
<li>数据库缓存</li>
<li>Memcache缓存(使用python-memcached模块)</li>
<li>Memcache缓存(使用pylibmc模块)</li>
</ul>
<p>经常使用的有文件缓存和Mencache缓存</p>
<h2 id="三-Django6种缓存的配置"><a href="#三-Django6种缓存的配置" class="headerlink" title="三 Django6种缓存的配置"></a>三 Django6种缓存的配置</h2><p><strong>1.2.1 开发调试(此模式为开发调试使用,实际上不执行任何操作)</strong></p>
<p>settings.py文件配置</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">CACHES = &#123;</span><br><span class="line"> <span class="string">'default'</span>: &#123;</span><br><span class="line">  <span class="string">'BACKEND'</span>: <span class="string">'django.core.cache.backends.dummy.DummyCache'</span>,  <span class="comment"># 缓存后台使用的引擎</span></span><br><span class="line">  <span class="string">'TIMEOUT'</span>: <span class="number">300</span>,            <span class="comment"># 缓存超时时间（默认300秒，None表示永不过期，0表示立即过期）</span></span><br><span class="line">  <span class="string">'OPTIONS'</span>:&#123;</span><br><span class="line">   <span class="string">'MAX_ENTRIES'</span>: <span class="number">300</span>,          <span class="comment"># 最大缓存记录的数量（默认300）</span></span><br><span class="line">   <span class="string">'CULL_FREQUENCY'</span>: <span class="number">3</span>,          <span class="comment"># 缓存到达最大个数之后，剔除缓存个数的比例，即：1/CULL_FREQUENCY（默认3）</span></span><br><span class="line">  &#125;,</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>1.2.2 内存缓存(将缓存内容保存至内存区域中)</strong></p>
<p>settings.py文件配置</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">CACHES = &#123;</span><br><span class="line"> <span class="string">'default'</span>: &#123;</span><br><span class="line">  <span class="string">'BACKEND'</span>: <span class="string">'django.core.cache.backends.locmem.LocMemCache'</span>,  <span class="comment"># 指定缓存使用的引擎</span></span><br><span class="line">  <span class="string">'LOCATION'</span>: <span class="string">'unique-snowflake'</span>,         <span class="comment"># 写在内存中的变量的唯一值 </span></span><br><span class="line">  <span class="string">'TIMEOUT'</span>:<span class="number">300</span>,             <span class="comment"># 缓存超时时间(默认为300秒,None表示永不过期)</span></span><br><span class="line">  <span class="string">'OPTIONS'</span>:&#123;</span><br><span class="line">   <span class="string">'MAX_ENTRIES'</span>: <span class="number">300</span>,           <span class="comment"># 最大缓存记录的数量（默认300）</span></span><br><span class="line">   <span class="string">'CULL_FREQUENCY'</span>: <span class="number">3</span>,          <span class="comment"># 缓存到达最大个数之后，剔除缓存个数的比例，即：1/CULL_FREQUENCY（默认3）</span></span><br><span class="line">  &#125;  </span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>1.2.3 文件缓存(把缓存数据存储在文件中)</strong></p>
<p>settings.py文件配置</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">CACHES = &#123;</span><br><span class="line"> <span class="string">'default'</span>: &#123;</span><br><span class="line">  <span class="string">'BACKEND'</span>: <span class="string">'django.core.cache.backends.filebased.FileBasedCache'</span>, <span class="comment">#指定缓存使用的引擎</span></span><br><span class="line">  <span class="string">'LOCATION'</span>: <span class="string">'/var/tmp/django_cache'</span>,        <span class="comment">#指定缓存的路径</span></span><br><span class="line">  <span class="string">'TIMEOUT'</span>:<span class="number">300</span>,              <span class="comment">#缓存超时时间(默认为300秒,None表示永不过期)</span></span><br><span class="line">  <span class="string">'OPTIONS'</span>:&#123;</span><br><span class="line">   <span class="string">'MAX_ENTRIES'</span>: <span class="number">300</span>,            <span class="comment"># 最大缓存记录的数量（默认300）</span></span><br><span class="line">   <span class="string">'CULL_FREQUENCY'</span>: <span class="number">3</span>,           <span class="comment"># 缓存到达最大个数之后，剔除缓存个数的比例，即：1/CULL_FREQUENCY（默认3）</span></span><br><span class="line">  &#125;</span><br><span class="line"> &#125;   </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>1.2.4 数据库缓存(把缓存数据存储在数据库中)</strong></p>
<p>settings.py文件配置</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">CACHES = &#123;</span><br><span class="line"> <span class="string">'default'</span>: &#123;</span><br><span class="line">  <span class="string">'BACKEND'</span>: <span class="string">'django.core.cache.backends.db.DatabaseCache'</span>,  <span class="comment"># 指定缓存使用的引擎</span></span><br><span class="line">  <span class="string">'LOCATION'</span>: <span class="string">'cache_table'</span>,          <span class="comment"># 数据库表    </span></span><br><span class="line">  <span class="string">'OPTIONS'</span>:&#123;</span><br><span class="line">   <span class="string">'MAX_ENTRIES'</span>: <span class="number">300</span>,           <span class="comment"># 最大缓存记录的数量（默认300）</span></span><br><span class="line">   <span class="string">'CULL_FREQUENCY'</span>: <span class="number">3</span>,          <span class="comment"># 缓存到达最大个数之后，剔除缓存个数的比例，即：1/CULL_FREQUENCY（默认3）</span></span><br><span class="line">  &#125;  </span><br><span class="line"> &#125;   </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意,创建缓存的数据库表使用的语句:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python manage.py createcachetable</span><br></pre></td></tr></table></figure>

<p><strong>1.2.5 Memcache缓存(使用python-memcached模块连接memcache)</strong></p>
<p>Memcached是Django原生支持的缓存系统.要使用Memcached,需要下载Memcached的支持库python-memcached或pylibmc.</p>
<p>settings.py文件配置</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">CACHES = &#123;</span><br><span class="line"> <span class="string">'default'</span>: &#123;</span><br><span class="line">  <span class="string">'BACKEND'</span>: <span class="string">'django.core.cache.backends.memcached.MemcachedCache'</span>, <span class="comment"># 指定缓存使用的引擎</span></span><br><span class="line">  <span class="string">'LOCATION'</span>: <span class="string">'192.168.10.100:11211'</span>,         <span class="comment"># 指定Memcache缓存服务器的IP地址和端口</span></span><br><span class="line">  <span class="string">'OPTIONS'</span>:&#123;</span><br><span class="line">   <span class="string">'MAX_ENTRIES'</span>: <span class="number">300</span>,            <span class="comment"># 最大缓存记录的数量（默认300）</span></span><br><span class="line">   <span class="string">'CULL_FREQUENCY'</span>: <span class="number">3</span>,           <span class="comment"># 缓存到达最大个数之后，剔除缓存个数的比例，即：1/CULL_FREQUENCY（默认3）</span></span><br><span class="line">  &#125;</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>LOCATION也可以配置成如下:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'LOCATION'</span>: <span class="string">'unix:/tmp/memcached.sock'</span>,   <span class="comment"># 指定局域网内的主机名加socket套接字为Memcache缓存服务器</span></span><br><span class="line"><span class="string">'LOCATION'</span>: [         <span class="comment"># 指定一台或多台其他主机ip地址加端口为Memcache缓存服务器</span></span><br><span class="line"> <span class="string">'192.168.10.100:11211'</span>,</span><br><span class="line"> <span class="string">'192.168.10.101:11211'</span>,</span><br><span class="line"> <span class="string">'192.168.10.102:11211'</span>,</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p><strong>1.2.6 Memcache缓存(使用pylibmc模块连接memcache)</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">settings.py文件配置</span><br><span class="line"> CACHES = &#123;</span><br><span class="line">  <span class="string">'default'</span>: &#123;</span><br><span class="line">   <span class="string">'BACKEND'</span>: <span class="string">'django.core.cache.backends.memcached.PyLibMCCache'</span>,  <span class="comment"># 指定缓存使用的引擎</span></span><br><span class="line">   <span class="string">'LOCATION'</span>:<span class="string">'192.168.10.100:11211'</span>,         <span class="comment"># 指定本机的11211端口为Memcache缓存服务器</span></span><br><span class="line">   <span class="string">'OPTIONS'</span>:&#123;</span><br><span class="line">    <span class="string">'MAX_ENTRIES'</span>: <span class="number">300</span>,            <span class="comment"># 最大缓存记录的数量（默认300）</span></span><br><span class="line">    <span class="string">'CULL_FREQUENCY'</span>: <span class="number">3</span>,           <span class="comment"># 缓存到达最大个数之后，剔除缓存个数的比例，即：1/CULL_FREQUENCY（默认3）</span></span><br><span class="line">   &#125;,  </span><br><span class="line">  &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<p>LOCATION也可以配置成如下:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'LOCATION'</span>: <span class="string">'/tmp/memcached.sock'</span>,  <span class="comment"># 指定某个路径为缓存目录</span></span><br><span class="line"><span class="string">'LOCATION'</span>: [       <span class="comment"># 分布式缓存,在多台服务器上运行Memcached进程,程序会把多台服务器当作一个单独的缓存,而不会在每台服务器上复制缓存值</span></span><br><span class="line"> <span class="string">'192.168.10.100:11211'</span>,</span><br><span class="line"> <span class="string">'192.168.10.101:11211'</span>,</span><br><span class="line"> <span class="string">'192.168.10.102:11211'</span>,</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>Memcached是基于内存的缓存,数据存储在内存中.所以如果服务器死机的话,数据就会丢失,所以Memcached一般与其他缓存配合使用</p>
<h2 id="四-Django中的缓存应用"><a href="#四-Django中的缓存应用" class="headerlink" title="四 Django中的缓存应用"></a>四 <strong>Django中的缓存应用</strong></h2><p>Django提供了不同粒度的缓存,可以缓存某个页面,可以只缓存一个页面的某个部分,甚至可以缓存整个网站.</p>
<p>数据库：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Book</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    name=models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">    price=models.DecimalField(max_digits=<span class="number">6</span>,decimal_places=<span class="number">1</span>)</span><br></pre></td></tr></table></figure>

<p><img src="https://tva1.sinaimg.cn/large/007S8ZIlgy1gj6s1tsurwj30m005ut98.jpg" alt="img"></p>
<h3 id="4-1-视图函数使用缓存"><a href="#4-1-视图函数使用缓存" class="headerlink" title="4.1 视图函数使用缓存"></a>4.1 视图函数使用缓存</h3><p>视图：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.views.decorators.cache <span class="keyword">import</span> cache_page</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="keyword">from</span> .models <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line"><span class="meta">@cache_page(15)          #超时时间为15秒</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">index</span><span class="params">(request)</span>:</span></span><br><span class="line">　　t=time.time()      <span class="comment">#获取当前时间</span></span><br><span class="line">　　bookList=Book.objects.all()</span><br><span class="line">　　<span class="keyword">return</span> render(request,<span class="string">"index.html"</span>,locals())</span><br></pre></td></tr></table></figure>

<p>模板(index.html):</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Title<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">h3</span>&gt;</span>当前时间:-----&#123;&#123; t &#125;&#125;<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">ul</span>&gt;</span></span><br><span class="line">    &#123;% for book in bookList %&#125;</span><br><span class="line">       <span class="tag">&lt;<span class="name">li</span>&gt;</span>&#123;&#123; book.name &#125;&#125;---------&gt;&#123;&#123; book.price &#125;&#125;$<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">    &#123;% endfor %&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>上面的例子是基于内存的缓存配置,基于文件的缓存该怎么配置呢??</p>
<p>更改settings.py的配置</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">CACHES = &#123;</span><br><span class="line"> <span class="string">'default'</span>: &#123;</span><br><span class="line">  <span class="string">'BACKEND'</span>: <span class="string">'django.core.cache.backends.filebased.FileBasedCache'</span>, <span class="comment"># 指定缓存使用的引擎</span></span><br><span class="line">  <span class="string">'LOCATION'</span>: <span class="string">'E:\django_cache'</span>,          <span class="comment"># 指定缓存的路径</span></span><br><span class="line">  <span class="string">'TIMEOUT'</span>: <span class="number">300</span>,              <span class="comment"># 缓存超时时间(默认为300秒,None表示永不过期)</span></span><br><span class="line">  <span class="string">'OPTIONS'</span>: &#123;</span><br><span class="line">   <span class="string">'MAX_ENTRIES'</span>: <span class="number">300</span>,            <span class="comment"># 最大缓存记录的数量（默认300）</span></span><br><span class="line">   <span class="string">'CULL_FREQUENCY'</span>: <span class="number">3</span>,           <span class="comment"># 缓存到达最大个数之后，剔除缓存个数的比例，即：1/CULL_FREQUENCY（默认3）</span></span><br><span class="line">  &#125;</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后再次刷新浏览器,可以看到在刚才配置的目录下生成的缓存文件</p>
<p>通过实验可以知道,Django会以自己的形式把缓存文件保存在配置文件中指定的目录中.</p>
<h3 id="4-2-全站使用缓存"><a href="#4-2-全站使用缓存" class="headerlink" title="4.2 全站使用缓存"></a>4.2 全站使用缓存</h3><p>既然是全站缓存,当然要使用Django中的中间件.</p>
<p>用户的请求通过中间件,经过一系列的认证等操作,如果请求的内容在缓存中存在,则使用FetchFromCacheMiddleware获取内容并返回给用户</p>
<p>当返回给用户之前,判断缓存中是否已经存在,如果不存在,则UpdateCacheMiddleware会将缓存保存至Django的缓存之中,以实现全站缓存</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">缓存整个站点，是最简单的缓存方法</span><br><span class="line"></span><br><span class="line">在 MIDDLEWARE_CLASSES 中加入 “update” 和 “fetch” 中间件</span><br><span class="line">MIDDLEWARE_CLASSES = (</span><br><span class="line">    ‘django.middleware.cache.UpdateCacheMiddleware’, <span class="comment">#第一</span></span><br><span class="line">    <span class="string">'django.middleware.common.CommonMiddleware'</span>,</span><br><span class="line">    ‘django.middleware.cache.FetchFromCacheMiddleware’, <span class="comment">#最后</span></span><br><span class="line">)</span><br><span class="line">“update” 必须配置在第一个</span><br><span class="line">“fetch” 必须配置在最后一个</span><br></pre></td></tr></table></figure>

<p>修改settings.py配置文件</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">MIDDLEWARE_CLASSES = (</span><br><span class="line">    <span class="string">'django.middleware.cache.UpdateCacheMiddleware'</span>,   <span class="comment">#响应HttpResponse中设置几个headers</span></span><br><span class="line">    <span class="string">'django.contrib.sessions.middleware.SessionMiddleware'</span>,</span><br><span class="line">    <span class="string">'django.middleware.common.CommonMiddleware'</span>,</span><br><span class="line">    <span class="string">'django.middleware.csrf.CsrfViewMiddleware'</span>,</span><br><span class="line">    <span class="string">'django.contrib.auth.middleware.AuthenticationMiddleware'</span>,</span><br><span class="line">    <span class="string">'django.contrib.auth.middleware.SessionAuthenticationMiddleware'</span>,</span><br><span class="line">    <span class="string">'django.contrib.messages.middleware.MessageMiddleware'</span>,</span><br><span class="line">    <span class="string">'django.middleware.clickjacking.XFrameOptionsMiddleware'</span>,</span><br><span class="line">    <span class="string">'django.middleware.security.SecurityMiddleware'</span>,</span><br><span class="line">    <span class="string">'django.middleware.cache.FetchFromCacheMiddleware'</span>,   <span class="comment">#用来缓存通过GET和HEAD方法获取的状态码为200的响应</span></span><br><span class="line"></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">CACHE_MIDDLEWARE_SECONDS=<span class="number">10</span></span><br></pre></td></tr></table></figure>

<p>视图函数：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.views.decorators.cache <span class="keyword">import</span> cache_page</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="keyword">from</span> .models <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">index</span><span class="params">(request)</span>:</span></span><br><span class="line"></span><br><span class="line">     t=time.time()      <span class="comment">#获取当前时间</span></span><br><span class="line">     bookList=Book.objects.all()</span><br><span class="line">     <span class="keyword">return</span> render(request,<span class="string">"index.html"</span>,locals())</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">foo</span><span class="params">(request)</span>:</span></span><br><span class="line">    t=time.time()      <span class="comment">#获取当前时间</span></span><br><span class="line">    <span class="keyword">return</span> HttpResponse(<span class="string">"HELLO:"</span>+str(t))</span><br></pre></td></tr></table></figure>

<p>模板(index.html)：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Title<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">h3</span> <span class="attr">style</span>=<span class="string">"color: green"</span>&gt;</span>当前时间:-----&#123;&#123; t &#125;&#125;<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">ul</span>&gt;</span></span><br><span class="line">    &#123;% for book in bookList %&#125;</span><br><span class="line">       <span class="tag">&lt;<span class="name">li</span>&gt;</span>&#123;&#123; book.name &#125;&#125;---------&gt;&#123;&#123; book.price &#125;&#125;$<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">    &#123;% endfor %&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>其余代码不变,刷新浏览器是10秒,页面上的时间变化一次,这样就实现了全站缓存.</p>
<h3 id="4-3局部视图缓存"><a href="#4-3局部视图缓存" class="headerlink" title="4.3局部视图缓存"></a><strong>4.3局部视图缓存</strong></h3><p>例子,刷新页面时,整个网页有一部分实现缓存</p>
<p>views视图函数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.views.decorators.cache <span class="keyword">import</span> cache_page</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="keyword">from</span> .models <span class="keyword">import</span> *</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">index</span><span class="params">(request)</span>:</span></span><br><span class="line">     t=time.time()      <span class="comment">#获取当前时间</span></span><br><span class="line">     bookList=Book.objects.all()</span><br><span class="line">     <span class="keyword">return</span> render(request,<span class="string">"index.html"</span>,locals())</span><br></pre></td></tr></table></figure>

<p>模板(index.html):</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&#123;% load cache %&#125;</span><br><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang&#x3D;&quot;en&quot;&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset&#x3D;&quot;UTF-8&quot;&gt;</span><br><span class="line">    &lt;title&gt;Title&lt;&#x2F;title&gt;</span><br><span class="line">&lt;&#x2F;head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line"> &lt;h3 style&#x3D;&quot;color: green&quot;&gt;不缓存:-----&#123;&#123; t &#125;&#125;&lt;&#x2F;h3&gt;</span><br><span class="line"></span><br><span class="line">&#123;% cache 2 &#39;name&#39; %&#125;</span><br><span class="line"> &lt;h3&gt;缓存:-----:&#123;&#123; t &#125;&#125;&lt;&#x2F;h3&gt;</span><br><span class="line">&#123;% endcache %&#125;</span><br><span class="line"></span><br><span class="line">&lt;&#x2F;body&gt;</span><br><span class="line">&lt;&#x2F;html&gt;</span><br></pre></td></tr></table></figure>



</section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/go/4-Go%E8%AF%AD%E8%A8%80%E6%A1%86%E6%9E%B6/4-1-gin%E6%A1%86%E6%9E%B6/8-GORM%E5%A2%9E%E5%88%A0%E6%9F%A5%E6%94%B9/">
        <span class="nav-arrow">← </span>
        
          go/4-Go语言框架/4-1-gin框架/8-GORM增删查改
        
      </a>
    
    
      <a class="nav-right" href="/python/Django%E6%A1%86%E6%9E%B6/6-%E8%A7%86%E5%9B%BE%E5%B1%82/">
        
          python/Django框架/6-视图层
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#一-缓存介绍"><span class="toc-nav-text">一 缓存介绍</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#二-Django中的6种缓存方式"><span class="toc-nav-text">二 Django中的6种缓存方式</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#三-Django6种缓存的配置"><span class="toc-nav-text">三 Django6种缓存的配置</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#四-Django中的缓存应用"><span class="toc-nav-text">四 Django中的缓存应用</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-1-视图函数使用缓存"><span class="toc-nav-text">4.1 视图函数使用缓存</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-2-全站使用缓存"><span class="toc-nav-text">4.2 全站使用缓存</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-3局部视图缓存"><span class="toc-nav-text">4.3局部视图缓存</span></a></li></ol></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/python/Django框架/19-Django高级之-缓存/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "python/Django框架/19-Django高级之-缓存",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>